//
//  LocationView.m
//  lumihui
//
//  Created by oceans on 2018/10/27.
//  Copyright © 2018 ios. All rights reserved.
//

#import "LocationView.h"
#import "LocationModel.h"
#import "LocalCache.h"
#import "UIView+Convinience.h"

@interface LocationView () <LocationModelDelegate>

@property (strong, nonatomic) UILabel *titleLabel;
@property (strong, nonatomic) UIButton *deleteButton;
@property (strong, nonatomic) LocationModel *locationModel;
@property (strong, nonatomic) UIImageView *iconImageView;
@end

@implementation LocationView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}

- (void)setup {
    
    self.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1.0];
    self.layer.cornerRadius = 4.5;
    self.layer.masksToBounds = YES;
    
    self.iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(7, 3, 17, 17)];
    self.iconImageView.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1.0];
    [self addSubview:_iconImageView];
    
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(29, 0, 0, 23)];
    self.titleLabel.font = [UIFont systemFontOfSize:13.0];
    _titleLabel.textColor = COLOR(164, 160, 166, 1);
    [self addSubview:_titleLabel];
    
    self.deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _deleteButton.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1.0];
    _deleteButton.frame = CGRectMake(0, 0, 23, 23);
    [_deleteButton setImage:[UIImage imageNamed:@"image_215"] forState:UIControlStateNormal];
    [_deleteButton addTarget:self action:@selector(deleteButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    _deleteButton.hidden = YES;
    [self addSubview:_deleteButton];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGes:)];
    [self addGestureRecognizer:tap];
}

- (void)didMoveToSuperview {
    [super didMoveToSuperview];
    BOOL isAutoShowLocation = [[LocalCache shared] getPlistBoolForKey:@"post_show_location"];
    if (isAutoShowLocation) {
        [self showLocation];
    }else {
        [self notShowLocation];
    }
}

- (LocationModel *)locationModel {
    if (!_locationModel) {
        _locationModel = [[LocationModel alloc] init];
        _locationModel.delegate = self;
    }
    return _locationModel;
}

- (void)showLocation {
    
    [self.locationModel startLocation];
}

- (void)notShowLocation {
    self.iconImageView.image = [UIImage imageNamed:@"image_214"];
    self.deleteButton.hidden = YES;
    [self calculateText:@"你在哪里？" WidthWithDeleteButton:NO];
}

- (void)calculateText:(NSString*)text WidthWithDeleteButton:(BOOL)with {
    
    if (text == nil || text.length == 0) {
        return;
    }
    
    self.titleLabel.text = text;
    CGRect textFrame = [text boundingRectWithSize:CGSizeMake(200, 20) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:13.0]} context:nil];
    if (with) {
        self.width = 29 + textFrame.size.width + 35;
        self.titleLabel.width = textFrame.size.width;
        self.deleteButton.x = self.width - 25;
    }else {
        self.width = 29 + textFrame.size.width + 13;
        self.titleLabel.width = textFrame.size.width;
    }
}

- (void)tapGes:(UITapGestureRecognizer*)tap {
    
    BOOL isAutoShowLocation = [[LocalCache shared] getPlistBoolForKey:@"post_show_location"];
    
    if (isAutoShowLocation == NO) {
        isAutoShowLocation = YES;
        
        [[LocalCache shared] setPlistBool:isAutoShowLocation forKey:@"post_show_location"];
        [self showLocation];
    }else if (self.locationModel.locationStatus == LocationStatusNotRequest || self.locationModel.locationStatus == LocationStatusNotAllow || self.locationModel.locationStatus == LocationStatusFailed) {
        [self showLocation];
    }
    
}

- (void)deleteButtonPressed:(UIButton*)sender {
    
    self.city = nil;
    _lat = 0;
    _lng = 0;
    [[LocalCache shared] setPlistBool:NO forKey:@"post_show_location"];
    [self notShowLocation];
}

#pragma mark - lnlocationmodel delegate

- (void)locationModel:(LocationModel *)model statusChanged:(LocationStatus)status {
    
    if (status == LocationStatusNoServices) {
        [self locationNotEanble];
        [self calculateText:@"无GPS服务" WidthWithDeleteButton:NO];
    }else if (status == LocationStatusFailed) {
        [self locationNotEanble];
        [self calculateText:@"定位失败" WidthWithDeleteButton:NO];
    }else if (status == LocationStatusNotAllow || status == LocationStatusNotRequest) {
        [self notShowLocation];
    }else if (status == LocationStatusLocating) {
        [self locationNotEanble];
        [self calculateText:@"定位中..." WidthWithDeleteButton:NO];
    }
}

- (void)locationModel:(LocationModel *)model locationFinished:(NSArray<CLLocation *> *)locations {
    
    if (locations && locations.count > 0) {
        
        CLLocation *currentLocation = [locations lastObject];
        _lat = currentLocation.coordinate.latitude;
        _lng = currentLocation.coordinate.latitude;
        CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
        
        __weak typeof(self) weakself = self;
        //反编码
        [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            if (placemarks.count > 0) {
                CLPlacemark *placeMark = placemarks[0];
                weakself.city = placeMark.locality;
//                if (! weakself.city) {
//                    weakself.city = @"济南";
//                }
                [weakself locationFinished];
            }
            else if (error == nil && placemarks.count == 0) {
                NSLog(@"No location and error return");
            }
            else if (error) {
                NSLog(@"location error: %@ ",error);
            }
            
        }];
    }
}

- (void)locationModel:(LocationModel *)model locationFailed:(NSError *)error {
    
    NSLog(@"%@", error.description);
}

- (void)locationNotEanble {
    self.iconImageView.image = [UIImage imageNamed:@"image_214"];
    self.deleteButton.hidden = YES;
}

- (void)locationFinished {
    self.iconImageView.image = [UIImage imageNamed:@"image_214"];
    self.deleteButton.hidden = NO;
    [self calculateText:self.city WidthWithDeleteButton:YES];
}

@end
